package com.touchfired.server.websocket;

import com.touchfired.common.properties.WebSocketServerProperties;
import com.touchfired.server.handler.WebSocketChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;

/**
 * 服务器启动主类
 *
 * @author 幸佳俊
 */
@Component
public class NettyServer {

    private final static Logger logger = LoggerFactory.getLogger(NettyServer.class);

    private EventLoopGroup parentGroup = new NioEventLoopGroup();
    private EventLoopGroup childGroup = new NioEventLoopGroup();
    private WebSocketServerProperties webSocketServerProperties;
    private WebSocketChannelInitializer webSocketChannelInitializer;

    public NettyServer(WebSocketServerProperties webSocketServerProperties, WebSocketChannelInitializer webSocketChannelInitializer) {
        this.webSocketServerProperties = webSocketServerProperties;
        this.webSocketChannelInitializer = webSocketChannelInitializer;
    }

    @PostConstruct
    public void start() throws Exception {
        ServerBootstrap bootstrap = new ServerBootstrap()
                .group(parentGroup, childGroup)
                .channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(webSocketServerProperties.getPort()))
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(webSocketChannelInitializer);
        ChannelFuture future = bootstrap.bind().sync();
        if (future.isSuccess()) {
            logger.info("netty启动完成：{}", webSocketServerProperties.getPort());
        }
    }

    /**
     * 销毁
     */
    @PreDestroy
    public void destroy() {
        parentGroup.shutdownGracefully().syncUninterruptibly();
        childGroup.shutdownGracefully().syncUninterruptibly();
    }
}
